<?php
declare(strict_types=1);

namespace app\admin\controller;

use app\admin\service\AliOosService;
use app\admin\service\ConfigService;
use app\admin\service\DemandService;
use app\admin\service\LocationService;
use app\admin\service\OfficialStaffService;
use app\admin\service\ResourceSaleBalanceService;
use app\admin\service\ResourceSaleWalletService;
use app\admin\service\UsersProfitLogService;
use app\admin\service\UsersService;
use app\admin\service\UsersWalletLogService;
use app\AdminController;
use app\admin\validate\Demand as demandValidate;
use think\exception\ValidateException;
use think\facade\Log;

class Demand extends AdminController
{
    /**
     * 需求列表
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        // 1=>交易中  2=>已售出  3=>待完善
        $type = intval($this->request->param('type', 1));
        if (request()->isPost()) {
            switch ($type) {
                case 2:
                    $status = ['2', '3'];
                    break;
                case 3:
                    $status = '0';
                    break;
                default:
                    $status = '1';
            }

            $where[] = ['d.status', 'in', $status];
            // 关键词搜索
            $keywords = trim($this->request->param('keywords', ''));
            if ($keywords) {
                $where[] = ['d.name|d.s_number|d.label|c.name', 'like', '%' . $keywords . '%'];
            }

            $list = DemandService::getDemandList($where, $this->page, $this->pagesize, $type);
            $count = DemandService::countDemandList($where);

            return adminResponseJson([
                'type' => $type,
                'list' => $list,
                'count' => $count
            ]);
        }

        // 当日新增
        $todayDemand = DemandService::todayDemand();
        // 本周新增
        $countDemandWeek = DemandService::countDemandWeek();
        // 当月新增
        $countDemandMonth = DemandService::countDemandMonth();
        // 总需求
        $countDemand = DemandService::countDemand();
        // 当月需求（折线图）
        $demandMonthLine = DemandService::getDemandMonthLine();

        // 交易中
        $buyDemand = DemandService::countDemandList(['d.status' => 1]);
        // 已售出
        $sellDemand = DemandService::countDemandList([['d.status', 'in', ['2', '3']]]);

        return view('', [
            'type' => $type,
            'demand_data' => [
                'todayDemand' => $todayDemand,
                'countDemandWeek' => $countDemandWeek,
                'countDemandMonth' => $countDemandMonth,
                'countDemand' => $countDemand,
                'demandMonthLine' => $demandMonthLine,
            ],
            'trade_data' => [
                'buyDemand' => $buyDemand,
                'buyLastDemand' => $countDemand - $buyDemand,
                'buyDemandScale' => round(($buyDemand / $countDemand) * 100, 2) . '%',
                'sellDemand' => $sellDemand,
                'sellLastDemand' => $countDemand - $sellDemand,
                'sellDemandScale' => round(($sellDemand / $countDemand) * 100, 2) . '%',
            ]
        ]);
    }

    /**
     * 需求添加
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function demandAdd()
    {
        if (request()->isPost()) {
            $data = $this->request->post();

            try {
                validate(demandValidate::class)->demandInsert()->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            $info = DemandService::findDemand(['name' => $data['name'], 'status' => 1, 'uid' => $data['uid']]);
            if ($info) {
                $this->error(adminJsonMsg(10021));
            }

            /**
             * 需求更改，这里不上传用户id
             * if (intval($data['uid']) < 1) {
             * $this->error(adminJsonMsg(1006));
             * }
             *
             * // 根据用户id查询是否存在此人
             * $users = UsersService::findUsers(['id' => $data['uid']]);
             * if (!$users) {
             * $this->error(adminJsonMsg(10010));
             * }
             * */

            // 获取最后一个自增id
            $lastId = DemandService::findDemandLastId();
            $lastId = $lastId ? ++$lastId : 1;
            // 获取编号
            $data['s_number'] = getResourceSaleNumber($data['group_number'], $lastId);
            $data['status'] = 1;
            $res = DemandService::createDemand($data);
            if (!$res) {
                $this->error(adminJsonMsg(1003));
            }

//            $imageArr[] = $data['qrcode'];
            $imageArr[] = $data['logo'];

            AliOosService::uploadAliOos($imageArr);

            $this->success(adminJsonMsg(1004), (STRING)url('/demand/index'));
        }
        // 工作人员
        $officialStaff = OfficialStaffService::getOfficialStaff();
        // 省份
        $province = LocationService::getProvince();
        return view('', ['officialStaff' => $officialStaff, 'province' => $province]);
    }

    /**
     * 需求编辑
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function demandEdit()
    {
        $id = intval($this->request->param('id', 0));
        if (!$id) {
            $this->error(adminJsonMsg(1001));
        }

        $info = DemandService::findDemand(['id' => $id]);
        $info['yqrcode'] = $info['qrcode'] ? config('url.url') . $info['qrcode'] : '';
        $info['ylogo'] = $info['logo'] ? config('url.url') . $info['logo'] : '';

        if (request()->isPost()) {
            $data = $this->request->post();

            try {
                validate(demandValidate::class)->demandEdit()->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            /**
             * 需求更改，这里不上传用户id
             * if (intval($data['uid']) < 1) {
             * $this->error(adminJsonMsg(1006));
             * }
             *
             * // 根据用户id查询是否存在此人
             * $users = UsersService::findUsers(['id' => $data['uid']]);
             * if (!$users) {
             * $this->error(adminJsonMsg(10010));
             * }
             * */

            if (!$data['status']) {
                $data['s_number'] = getResourceSaleNumber($data['group_number'], $data['id']);
            } else {
                // 修改了群人数
                if ($data['group_number'] != $info['group_number']) {
                    // 修改编号
                    $s_number = substr_replace($info['s_number'], getResourceSaleNumber($data['group_number'], 0), 0, 1);
                    $data['s_number'] = $s_number;
                }
            }

            $data['status'] = 1;
            $res = DemandService::updateDemand($data, ['id' => $data['id']]);

            if (!$res) {
                $this->error(adminJsonMsg(1003));
            }

            $pathArr = [];
            $addArr = [];

            // 更改了logo
            if ($data['logo'] != $info['logo']) {
                $pathArr[] = $info['logo'];
                $addArr[] = $data['logo'];
            }

//            // 更改了二维码
//            if ($data['qrcode'] != $info['qrcode']) {
//                $pathArr[] = $info['qrcode'];
//                $addArr[] = $data['qrcode'];
//            }

            AliOosService::uploadAliOos($addArr);

            $this->success(adminJsonMsg(1004), (STRING)url('/demand/index'));
        }

        // 工作人员
        $officialStaff = OfficialStaffService::getOfficialStaff();
        // 省份
        $province = LocationService::getProvince();
        // 城市
        $city = LocationService::getCity($info['province']);
        // 地区
        $area = LocationService::getArea($info['city']);
        return view('', [
            'info' => $info,
            'officialStaff' => $officialStaff,
            'province' => $province,
            'city' => $city,
            'area' => $area,
        ]);
    }

    /**
     * 需求详情
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function demandShow()
    {
        $id = intval($this->request->param('id', 0));
        if (!$id) {
            $this->error(adminJsonMsg(1001));
        }
        $info = DemandService::findDemand(['id' => $id]);
        $info['qrcode'] = $info['qrcode'] ? config('url.url') . $info['qrcode'] : '';
        $info['logo'] = $info['logo'] ? config('url.url') . $info['logo'] : '';
        $info['tname'] = $info['tid'] == 1 ? '企业社群' : '个人社群';
        // 省份
        $info['province'] = LocationService::getLocationValue(['location_id' => $info['province']]);
        // 城市
        $info['city'] = LocationService::getLocationValue(['location_id' => $info['city']]);
        // 地区
        $info['area'] = LocationService::getLocationValue(['location_id' => $info['area']]);
        // 登记人
        $info['enroll_name'] = OfficialStaffService::findOfficialStaffValue(['id' => $info['enroll_id']]);
        return view('', ['info' => $info, 'source' => intval($this->request->param('source', 0))]);
    }

    /**
     * 状态修改
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function changeStatus()
    {
        $id = intval($this->request->param('id', 0));
        if (!$id) {
            $this->error(adminJsonMsg(1001));
        }
        $source = intval($this->request->param('source', 0));
        $field = trim($this->request->param('field', 'status'));

        $where = ['id' => $id];
        $info = DemandService::findDemand(['id' => $id]);
        if (!$info) {
            $this->error(adminJsonMsg(1002));
        }

        $res1 = $res = true;
        // 删除
        if ($source == 2) {
            $changeFields = -1;

            // 通过审核，写入售卖人收益和钱包（收益）记录
        } else {

            // 手续比例
            $handling_fee = $this->request->param('handling_fee') ? $this->request->param('handling_fee') / 100 : ConfigService::findConfigValue();
            // 计算手续费用
            $balance = $info['price'] * $handling_fee;
            // 实际收益
            $actualIncome = $info['price'] - $balance;
            $res = UsersProfitLogService::createUsersProfitLog([
                'uid' => $info['uid'],
                'title' => '转让社群成功',
                'sub_title' => $info['name'],
                'money' => $actualIncome,
                'profit' => '+' . $actualIncome,
                'handling_fee' => $handling_fee,
            ]);
            Log::write('创建用户收益记录' . json_encode($res), 'error');


            $map = ['uid' => $info['uid']];
            $usersWallet = UsersWalletLogService::findUsersWalletLog($map);
            if ($usersWallet) {
                $res1 = UsersWalletLogService::updateUsersWalletLog([
                    'can_withdrawal' => $usersWallet['can_withdrawal'] + $actualIncome,
                    'total_income' => $usersWallet['total_income'] + $actualIncome,
                ], $map);
                $write = '更新';
            } else {
                $res1 = UsersWalletLogService::createUsersWalletLog([
                    'uid' => $info['uid'],
                    'can_withdrawal' => $actualIncome,
                    'total_income' => $actualIncome,
                ]);
                $write = '创建';
            }
            Log::write($write . '用户钱包记录' . json_encode($res1), 'error');

            /**
             * ps：云链路5.0需求更改
             *
             * //            // 售卖人原余额
             * //            $seller = ResourceSaleBalanceService::findResourceSaleBalance(['uid' => $info['uid']]);
             * //            // 累加收益
             * //            $sellerBalance = (isset($seller['balance']) ? $seller['balance'] : 0) + $actualIncome;
             * //            if (!$seller) {
             * //                // 创建售卖人余额记录
             * //                $res = ResourceSaleBalanceService::createResourceSaleBalance([
             * //                    'uid' => $info['uid'],
             * //                    'balance' => $sellerBalance,
             * //                    'create_time' => time(),
             * //                ]);
             * //                Log::write('创建售卖人余额记录' . json_encode($res), 'error');
             * //
             * //            } else {
             * //                // 更新售卖人余额记录
             * //                $res = ResourceSaleBalanceService::updateResourceSaleBalance([
             * //                    'balance' => $sellerBalance,
             * //                    'update_time' => time(),
             * //                ], ['id = ?' => $seller['id']]);
             * //                Log::write('更新售卖人余额记录' . json_encode($res), 'error');
             * //            }
             * //
             * //
             * //            // 创建钱包（收益）记录
             * //            $res1 = ResourceSaleWalletService::createResourceSaleWallet([
             * //                'uid' => $info['uid'],
             * //                'sid' => $info['id'],
             * //                'moneys' => '+' . $actualIncome,
             * //                'balance' => $sellerBalance,
             * //                'desc' => '已出售社群：' . $info['name'],
             * //                // 类型 1已购买  2已出售
             * //                'type' => 2,
             * //                'handling_fee' => $handling_fee,
             * //                'original_income' => $info['price'],
             * //                'create_time' => time(),
             * //                'create_date' => date('Y年m月', time()),
             * //            ]);
             * //            Log::write('创建钱包（收益）记录' . json_encode($res1), 'error');
             *
             */

            $changeFields = 3;
        }
//        var_dump($field,$sort,$changeFields,$where);exit;
        $result = DemandService::updateDemand([$field => $changeFields], $where);
        if (!$res || !$res1 || !$result) {
            $this->error(adminJsonMsg(1003));
        }

        $this->success(adminJsonMsg(1004));
    }
}